<?php
    $item_menu[0] = 5;
    $item_menu[1] = 5   ;
    $title = 'Editar Publicidad';    
	
    if (!defined('URL')) { include('header.php'); }
    
	if (!isset($_SESSION["admin"])) {redirect("login.php");	exit(); }


    $submit     = request('submit','');
	$id     	= request('id',0);
    $familia_id = request('familia_id',0);
    

    if($_POST['submit']){

        $data = $_POST;
        $familia_id = $data['familia_id'];        

        if ($familia_id==0){
            $data['plan_id'] = $data['plan_id_home'];
        } else {
            $data['plan_id'] = $data['plan_id_interna'];
        }


        unset($data['plan_id_interna']);
        unset($data['plan_id_home']);
        unset($data['submit']);
        unset($data['test']);


        $db->debug = false;
        $ok = $db->Replace('publicidades', $data,'id', $autoquote = true); 

        if ($ok) { 
            $_SESSION['Msg'] = 'Publicidad se guardo correctamente.';
            redirect('publicidades_izq.php?accion=listar&familia_id='.$familia_id);
            exit();
               
        } else { 
            $_SESSION['Msg'] = '<br/>ERROR!! No se pudo guardar la Publicidad.'; 
            redirect('publicidades_izq.php?accion=listar&familia_id='.$familia_id);
            exit();
        }




    } else {
    	$cond 	= "select * from publicidades where id='$id'";
    	$rs 	= $db->SelectLimit($cond, 1);
    	$data	= $rs->FetchRow();

    }
    

    // -ARMA LOS SELECT DE LAS FAMILIAS
    $Familias = crearArbol(0);
    $parent_id = 0;
    $select_familia = '<select name="familia_id" id="familia_id" class="required">';
    $select_familia.= "<option value='0' >Página Principal</option>";
    foreach($Familias as $dd){
            if ($data['familia_id'] == $dd['id']) { $sel = "selected='selected'"; } else {$sel='';}
            $separador = "";
            if ($dd['nivel'] == 2 ) {
                $separador = "------";
            } elseif ($dd['nivel'] == 3 ) {
                $separador = "------------";
            } elseif ($dd['nivel'] == 4 ) {
                $separador = "------------------";
            }
            $select_familia.= "<option value='{$dd['id']}' $sel >$separador {$dd['nombre1']}</option>";
    }
    $select_familia.= "</select>";


    // -ARMA LOS SELECT DE LOS PLANES
    $sql = "select * from planes where LEFT(ubicacion,1)='I' and activo=1";
    $rs  = $db->Execute($sql);
    $Planes = $rs->GetRows();
    $select_plan_home = '<select name="plan_id_home" >';
    foreach($Planes as $dd){
        if($dd['ubicacion']=='IH'){
            if ($data['plan_id'] == $dd['id']) { $sel = "selected='selected'"; } else {$sel='';}
            $select_plan_home.= "<option value='{$dd['id']}' $sel >{$dd['plan']} -> {$dd['vigencia']}días -> {$dd['importe']}$</option>";
        }    
    }
    $select_plan_home.= "</select>";

    $select_plan_interna = '<select name="plan_id_interna" >';
    foreach($Planes as $dd){
        if($dd['ubicacion']=='II'){
            if ($data['plan_id'] == $dd['id']) { $sel = "selected='selected'"; } else {$sel='';}
            $select_plan_interna.= "<option value='{$dd['id']}' $sel >{$dd['plan']} -> {$dd['vigencia']}días -> {$dd['importe']}$</option>";
        }    
    }
    $select_plan_interna.= "</select>";





    // Estadisticas de Visita
    $sql = "select count(id) as cuantos, semana from visitas_unicas where publicidad_id='{$data['id']}' and visualizacion=1  group by semana order by fecha ASC";
    $rs  = $db->Execute($sql);
    $Visitas = $rs->GetRows();

    // Estadisticas de Click
    $sql = "select count(id) as cuantos, semana from visitas_unicas where publicidad_id='{$data['id']}' and click=1 group by semana order by fecha ASC";
    $rs  = $db->Execute($sql);
    $Click = $rs->GetRows();

    // Detalle de Pagos
    $sql = "select pagos.*,planes.plan from pagos 
            left join planes on pagos.plan_id = planes.id
            where publicidad_id='{$data['id']}'  order by pagos.desde DESC";
    $rs  = $db->Execute($sql);
    $Pagos = $rs->GetRows();

?>

<script type="text/javascript" src="<?php echo URL;?>/js/jquery.min.js"></script>
<script type="text/javascript" src="<?php echo URL;?>/js/jquery-validation-1.9.0/jquery.validate.js"></script>
<script type="text/javascript" src="<?php echo URL;?>/js/jquery-validation-1.9.0/localization/messages_es.js"></script>
<style type="text/css">
label { float: left; }
label.error { float: none; color: red; padding-left:0px; vertical-align: top; display: block;font-size:12px;}
p { clear: both; }
em { font-weight: bold; padding-right: 1em; vertical-align: top; color:red;}

</style>



<script>
    $(document).ready(function(){
        $.validator.setDefaults({ ignore: [] });        
        var validator = $("#form1").validate({
              invalidHandler: function() {
                $("#summary").text("Hay " + validator.numberOfInvalids() + " dato(s) NO valido(s). Por favor revise todas las secciones y complételos. Gracias.");
                $("#summary").show();
              }            
        });
        
        
    });
</script>


<!-- Menu Pestañas -->
<script type="text/javascript" src="<?php echo URL;?>/js/menupestanas/menupestanas.js"></script>
<link rel="stylesheet" href="<?php echo URL;?>/js/menupestanas/menupestanas.css" type="text/css" media="screen" />    

<script type="text/javascript" src="<?php echo URL;?>/js/ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="<?php echo URL;?>/js/ckfinder/ckfinder.js"></script>
<script type="text/javascript" src="<?php echo URL;?>/admin/productos_editar.js"></script>

<style>
.required { border:1px solid #FF9900; background:#eee;}
</style>

<?php if(!empty($_SESSION['Msg'])) { echo mensaje_ok($_SESSION['Msg']); $_SESSION['Msg']=''; } ?>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<center>

    <div id='summary' style='color:#FF0000; font-size:16px; font-weight:bold;line-height:24px; border:1px solid #FF0000;display:none;margin-bottom:20px;background:#F7D3D3;'></div>
    <ul class="tabs">
        <li><a href="#p_datos"> Datos Generales</a></li>
        <li><a href="#p_lecturas">Visualizaciones</a></li>
        <li><a href="#p_click">Click</a></li>
        <li><a href="#p_pagos">Pagos</a></li>
    </ul>

    <div class="tab_container">
        <div id="p_datos" class="tab_content" style='min-height:400px;width:850px;background:#FFF;'>
            <?php include('publicidades_izq_editar_datos.php'); ?>
        </div>

        <div id="p_lecturas" class="tab_content" style='min-height:400px;width:850px;background:#FFF;'>
            <div class='grid_4 ctitulo' >Visualizaciones totales de anuncio de <b><?php echo $data['titulo'];?></b>: <?php echo $data['lecturas'];?></div>
            <?php if(!empty($Visitas) and count($Visitas)>1) { ?>
                <div class='grid_8'>
                    
                        <script type="text/javascript">
                          google.load("visualization", "1", {packages:["corechart"]});
                          google.setOnLoadCallback(drawChart);
                          function drawChart() {
                            var data = google.visualization.arrayToDataTable([
                              ['Semana', 'Visitas'],
                              <?php foreach($Visitas as $v){ ?>
                                    ['<?php echo $v["semana"];?>',  <?php echo $v["cuantos"];?>],
                                <?php } ?>
                            ]);


                         new google.visualization.LineChart(document.getElementById('chart_div')).
                          draw(data, {curveType: "function",
                                        title: 'Visitas por Semana',
                                      width: 900, height: 500}
                              );

                          }
                    </script>
                    <div id="chart_div" style="width: 900px; height: 500px;"></div>
                </div>
            <?php } ?>

        </div>
        <div id="p_click" class="tab_content" style='min-height:400px;width:850px;background:#FFF;'>
            <div class='grid_4 ctitulo' >Click totales de anuncio de <b><?php echo $data['titulo'];?></b>: <?php echo $data['click'];?></div>
            <?php if(!empty($Click) and count($Click)>1) { ?>
                <div class='grid_8'>
                    
                        <script type="text/javascript">
                          google.load("visualization", "1", {packages:["corechart"]});
                          google.setOnLoadCallback(drawChart);
                          function drawChart() {
                            var data = google.visualization.arrayToDataTable([
                              ['Semana', 'Visitas'],
                              <?php foreach($Click as $v){ ?>
                                    ['<?php echo $v["semana"];?>',  <?php echo $v["cuantos"];?>],
                                <?php } ?>
                            ]);


                         new google.visualization.LineChart(document.getElementById('chart_click')).
                          draw(data, {curveType: "function",
                                        title: 'Clicks por Semana',
                                      width: 900, height: 500}
                              );

                          }
                    </script>
                    <div id="chart_click" style="width: 900px; height: 500px;"></div>
                </div>
            <?php } ?>
        </div>

        <div id="p_pagos" class="tab_content" style='min-height:400px;width:850px;background:#FFF;'>
            <?php include('publicidades_pagos.php');?>
        </div>

    </div>

</center>
<?php //pr($data);?>